package com.golang.api.interceptor;

import cn.hutool.json.JSONUtil;
import com.golang.api.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Sign拦截器，校验签名
 */
@Slf4j
@Component
public class SignInterceptor extends AbstractHandlerInterceptorAdapter {

    /**
     * 默认超时时间间隔：10分钟
     */
//    public static final Long INTERVAL = 10 * 60 * 1000L;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String appKey = RequestUtil.getRequestParam(request, "app_key");
        String sign = RequestUtil.getRequestParam(request, "sign");
        long timestamp = 0L;
        String tt = RequestUtil.getRequestParam(request, "timestamp");
        if (StringUtils.isNotBlank(tt)) {
            timestamp = Long.parseLong(tt);
        }

        // 签名必选参数验证
        if (StringUtils.isBlank(appKey) || StringUtils.isBlank(sign) || timestamp == 0L) {
            log.error("签名验证失败: 参数错误 appKey={}, sign={}, timestamp={}", appKey, sign, timestamp);
            super.responseErrorData(response, new Result<>(500, "参数错误"));
            return false;
        }

        MultiValueMap<String, String> params = RequestUtil.getRequestParams(request);
        params.remove("sign");
        params.remove("token");


//        // 请求超时验证
//        if (!checkTime(INTERVAL, timestamp)) {
//            log.debug("签名验证失败: 请求超时, current={}, timestamp={}, params={}", System.currentTimeMillis(), timestamp, JSONUtil.toJsonStr(params));
//            super.responseErrorData(response, new Result<>(500, "请求超时"));
//            return false;
//        }


        String appSecret = "1234567890abcdef";

        if (!SignUtils.checkSign(params, appSecret, sign)) {
            String correctSign = SignUtils.getSign(params, appSecret);
            log.debug("签名验证失败:  appKey={}, appSecret={}, errorSign={}, correctSign={}, params={}", appKey, appSecret, sign, correctSign, JSONUtil.toJsonStr(getRequestParams(request)));
            super.responseErrorData(response, new Result<>(500, "签名错误"));
            return false;
        }
        return true;
    }

    private static boolean checkTime(Long interval, Long timestamp) {
        if (null == timestamp || null == interval) {
            return false;
        }
        long ct = System.currentTimeMillis();
        return (Math.abs(ct - timestamp) <= interval);
    }

    public static void main(String[] args) {

        String ddd = "1234567890abcdefactivityClassification0activityIntroductionactivityTitleactivityType0app_keygolangcityCodecurrent1endTimesize10startTimetagld0timestamp1742307037371token1231234567890abcdef";
        System.out.println(MD5Util.md5Hex(ddd));


        System.out.println(System.currentTimeMillis());
    }
}
